from django.shortcuts import render

# Create your views here.


from rest_framework.viewsets import GenericViewSet
from rest_framework.decorators import action
from rest_framework.response import Response
from app01.models import Group, Users, Chat, Friendship,Groupname
from .serializer import Userserializers, Friendshipserializers, Groupserializers,Groupnameserializers,Groupsserializers
import hashlib


def encrypted_data(data):
    data = str(data)
    md5 = hashlib.md5(data.encode('utf-8'))
    return md5.hexdigest()


def generate_token(data):
    data1 = {'code': 123}
    data2 = {'resdfdd': 'fsfsfsfs'}
    token = f"{encrypted_data(data1)}.{encrypted_data(data2)}.{encrypted_data(data)}"
    return token


class LoginRregisterView(GenericViewSet):
    queryset = Users.objects.all()
    serializer_class = Userserializers

    @action(methods=['POST'], detail=False)
    def login(self, request):
        data = self.request.data

        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        validated_data = serializer.validated_data
        token = validated_data.pop('token')
        user = Users.objects.filter(**validated_data).first()
        if user:
            return Response({'code': 100, 'msg': '登陆成功', 'token': token})
        else:
            return Response({'code': 101, 'msg': '用户名或密码错误'})

    @action(methods=['POST'], detail=False)
    def register(self, request):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({'code': 100, 'msg': '注册成功'})


from app01.authentication import LoginAuth


class UserView(GenericViewSet):
    queryset = Users.objects.all()
    serializer_class = Userserializers
    authentication_classes = [LoginAuth]

    @action(methods=['GET'], detail=False)
    def userinform(self, request):
        data = self.get_queryset()
        ser = self.get_serializer(instance=data, many=True)
        return Response({'code': 100, 'results': ser.data})


class FriendsView(GenericViewSet):
    queryset = Friendship.objects.all()
    serializer_class = Friendshipserializers
    authentication_classes = [LoginAuth]

    @action(methods=['POST'], detail=False)
    def friends(self, request):
        friendshipobj=Friendship.objects.filter(**request.data).first()
        if friendshipobj:
            return Response({'code': 101, 'msg': '已申请'})
        else:
            serializer = self.get_serializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            serializer.save()
            return Response({'code': 100, 'msg': '申请成功'})

    @action(methods=['GET'], detail=False)
    def friend(self, request):
        username = request.GET.get('username')
        is_accepted = request.GET.get('is_accepted')
        if is_accepted == 'false':
            is_accepted = False
            friendship = Friendship.objects.filter(users_b=username, is_accepted=is_accepted)
            serializer = self.get_serializer(instance=friendship, many=True)
            data = serializer.data
        else:
            is_accepted = True
            friendship = Friendship.objects.filter(users_b=username, is_accepted=is_accepted)
            ser1 = self.get_serializer(instance=friendship, many=True)
            friendship1 = Friendship.objects.filter(users_a=username, is_accepted=is_accepted)
            ser2 = self.get_serializer(instance=friendship1, many=True)
            data = [{'name': i['users_a']} for i in ser1.data] + [{'name': i['users_b']} for i in ser2.data]
        return Response({'code': 100, 'results': data})

    @action(methods=['PUT'], detail=False)
    def addfriend(self, request):
        data = self.get_queryset()
        serializer = self.get_serializer(data=request.data, instance=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({'code': 100, 'results': '添加成功'})


class ChatsView(GenericViewSet):
    queryset = Group.objects.all()
    serializer_class = Groupserializers
    authentication_classes = [LoginAuth]

    @action(methods=['GET'], detail=False)
    def chatmessage(self, request):
        username = request.GET.get('username')
        toname = request.GET.get('toname')
        groupname = f'{username}-{toname}'
        togroupname = f'{toname}-{username}'
        obj = Group.objects.filter(groupname=str(groupname)).all()
        obj2 = Group.objects.filter(groupname=str(togroupname)).all()
        ser1 = self.get_serializer(instance=obj, many=True)
        ser2 = self.get_serializer(instance=obj2, many=True)
        combined_data = ser1.data + ser2.data

        data = sorted(combined_data, key=lambda x: x['chat']['msg_date'])
        return Response({'code': 100, 'results': data})

    @action(methods=['POST'], detail=False)
    def chatmsg(self, request):
        username = request.data.get('username')
        # @xx:msg
        msg = request.data.get('msg')
        groupname = f"{username}-{msg[1:].split(':')[0]}"
        # 创建聊天消息
        chat = Chat.objects.create(username=username, msg=msg)
        # 创建群组并关联聊天消息
        group = Group.objects.create(groupname=groupname, chat=chat)
        user = Users.objects.get(username=username)
        group.user.add(user)

        return Response({'code': 100, 'results': '添加成功'})


    @action(methods=['POST'], detail=False)
    def groupchatmsg(self, request):
        print(request.data)
        username = request.data.get('username')
        groupname = request.data.get('groupname')
        # @xx:msg
        msg = request.data.get('msg')

        # 创建聊天消息
        chat = Chat.objects.create(username=username, msg=msg)
        # 创建群组并关联聊天消息
        Group.objects.create(groupname=groupname, chat=chat,Singlechat=False)


        return Response({'code': 100, 'results': '添加成功'})

    @action(methods=['GET'], detail=False)
    def groupchatmessage(self, request):
        groupname = request.GET.get('groupname')
        print(groupname)
        obj = Group.objects.filter(groupname=groupname,Singlechat=False).all()
        ser = self.get_serializer(instance=obj, many=True)
        return Response({'code': 100, 'results': ser.data})




class GroupView(GenericViewSet):
    queryset = Groupname.objects.all()
    serializer_class = Groupsserializers
    authentication_classes = [LoginAuth]

    @action(methods=['GET'], detail=False)
    def creatgroup(self,request):
        namelist=request.GET.getlist('username[]')
        groupname=request.GET.get('groupname')
        obj=Groupname.objects.filter(name=groupname).first()
        if obj:
            return Response({'code': 101, 'results': '已存在'})
        else:
            group = Groupname.objects.create(name=groupname)
            for username in namelist:
                user = Users.objects.get(username=username)
                group.user.add(user)
            return Response({'code': 100, 'results': 'ok'})

    @action(methods=['GET'], detail=False)
    def groupname(self, request):
        username = request.GET.get('username')
        userobj=Users.objects.filter(username=username).first()
        obj = Groupname.objects.filter(user=userobj)
        ser = self.get_serializer(instance=obj, many=True)
        return Response({'code': 100, 'results': ser.data})